using System;
using Commons.Daos.Stats;
using Commons.Events;
using Commons.Models.Definitions;
using Commons.Models.OperationsContext;
using Commons.Models.Stats;
using Commons.Services.TradeValues;

namespace Commons.Services.Stats
{
	public delegate void UserStatsUpdateHandler(object sender, EventArgs e);
	public delegate void LevelUpHandler(object sender, LevelUpEventArgs e);

	public class UserStatsService : IUserStatsService
	{
		public event UserStatsUpdateHandler UserStatsUpdated;
		public event LevelUpHandler LevelUp;

		public IUserStatsDao UserStatsDao { protected get; set; }
		public ITradeService TradeService { protected get; set; }

		public UserStats GetStats()
		{
			return UserStatsDao.Get();
		}

		public void UpdateStats(UserStats stats)
		{
			if (stats.HasChanges())
			{
				CheckForNewLevels(stats);

				UserStatsDao.Update(stats);

				if (UserStatsUpdated != null)
				{
					UserStatsUpdated(this, EventArgs.Empty);
				}
			}
		}

		protected void CheckForNewLevels(UserStats stats)
		{
			foreach (IStat stat in stats.GetStats())
			{
				if (stat is LeveledStat)
				{
					LeveledStat leveledStat = (LeveledStat) stat;
					foreach (LevelDefinition level in leveledStat.GetUpdatedLevels(true))
					{
						TradeService.ProcessReward(level.Reward, new BasicOperationContext());

						if (LevelUp != null)
						{
							LevelUp(this, new LevelUpEventArgs(level));
						}
					}
				}
			}
		}
	}
}
